package com.weituotian.system.service.impl;

import com.weituotian.core.jpa.domain.SimpleSpecification;
import com.weituotian.core.jpa.domain.Specification;
import com.weituotian.core.result.Option;
import com.weituotian.core.utils.PageInfo;
import com.weituotian.system.dao.IBaseDao;
import com.weituotian.system.dao.IResourceDao;
import com.weituotian.system.dao.IRoleDao;
import com.weituotian.system.dao.IUserDao;
import com.weituotian.system.entity.Role;
import com.weituotian.system.entity.User;
import com.weituotian.system.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;

/**
 * 角色服务
 * Created by ange on 2016/9/26.
 */
@Service("roleService")
@Transactional
public class RoleService extends AdminBaseService<Role, Integer> implements IRoleService {

    private final IUserDao userDao;

    private final IRoleDao roleDao;

    private final IResourceDao resourceDao;

    @Autowired
    public RoleService(IUserDao userDao, IRoleDao roleDao, IResourceDao resourceDao) {
        this.userDao = userDao;
        this.roleDao = roleDao;
        this.resourceDao = resourceDao;
    }


    @Override
    public IBaseDao<Role, Integer> getBaseDao() {
        return roleDao;
    }

    @Override
    public Specification<Role> pageSpecification(PageInfo<?> pageInfo) {
        return new SimpleSpecification<Role>() {
            @Override
            public Predicate toPredicate(Root<Role> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

                List<Predicate> predicates = new ArrayList<Predicate>();

                //拼接查询条件
                for (Map.Entry<String, Object> entry : pageInfo.getCondition().entrySet()) {
                    String name = entry.getKey();
                    String value = (String) entry.getValue();
                    if (name.equals("name")) {
                        predicates.add(cb.like(root.get("name"), "%" + value + "%"));
                    } else {
                        predicates.add(cb.equal(root.get(name), value));
                    }
                }

                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
    }


    public Map<Integer, String> getOpenStatus() {
        Map<Integer, String> radio = new HashMap<>();
        radio.put(0, "关");
        radio.put(1, "开");
        return radio;
    }

    @Override
    public void deleteByIdsSafe(Integer[] ids) {
        for (Integer id : ids) {
            Role role = roleDao.findOne(id);
            role.getUsers().clear();
            roleDao.delete(role);
//            System.out.print("asd");
        }
    }

    public List<Option> getAllRoleListByUser(Integer userId) {
        return null;
    }

    public List<Integer> findRoleIdListByUserId(Integer userId) {
//        return userRoleMapper.findRoleIdListByUserId(userId);
        return null;
    }

    /**
     * 根据用户查询id,为所有的role生成一个对应html的option的对象
     * 如果该用户有该角色的话,option会被设置选中
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public List<Option> findAllRolesOptionsByUserId(Integer userId) {
        User user = userDao.findOne(userId);
        List<Role> userRoles = user.getRoles();
        List<Role> allRoles = roleDao.findAll();
        List<Option> options = new ArrayList<>();
        for (Role role : allRoles) {
            Option option = new Option(role.getName(), Integer.toString(role.getId()), "");
            if (userRoles.contains(role)) {
                option.setSelected("checked");//设置选中
            }
            options.add(option);
        }
        return options;
    }


    public void grant(Integer roleId, Integer[] resIds) {
        Role role = findById(roleId);
        role.setResources(resourceDao.findIds(resIds));

        /*
        //先删除该用户的所有角色
        int rows = roleResourceMapper.deleteAllRoleResources(roleId);
        if (rows < 0) {
            throw new ServiceException("更新前先删除角色的所有资源失败!");
        }

        if (resIds != null && resIds.length > 0) {
            rows = roleResourceMapper.insertAllResource(roleId, resIds);
            if (rows <= 0) {
                throw new ServiceException("角色的资源插入失败");
            }
        }
        */
    }


}
